$(document).ready(function(){
	var type=$('#type').val();
	var userId=$('#userId').val();
	//初始化form表单
	initForm(type,userId);
	
	//事件绑定
	eventBind(type,userId);
});

//初始化form表单
function initForm(type,userId){
	$('#userForm').validation();
	initDatePickers();
	
	if(type=='add'){
		genDictSelect('sexInfo','sex','1');
		genDictSelect('goodatInfo','goodat','1');
		genDictSelect('positionCode','position','1');
		//初始化用户类型下拉框
		initUserTypeSel(null);
		//初始化所属医院级拉框
		initHospitalSel(null,null);
		//初始化用户角色
		initUserRoles(null);
	}else{
		$.getApiClient('/user/{userid}').setQuery({userid: userId}).get().done(function(data){
			if(data.code=='0'){
				var payload=data.payload;
				$('#userForm').bindData(payload);
				$('#user_code').attr('readonly','readonly');
				$('#account_name').attr('readonly','readonly');
				genDictSelect('sexInfo','sex',payload.sex);
				genDictSelect('goodatInfo','goodat',payload.goodat);
				genDictSelect('positionCode','position',payload.position_code);
				//初始化用户类型下拉框
				initUserTypeSel(payload.user_type);
				//初始化所属医院级拉框
				initHospitalSel(payload.hospital_id,payload.department_id);
				//初始化用户角色
				initUserRoles(payload.role_id);
			}
		})
		
		//本人不可用修改自己的用户类型
		if(userId==loginUser.id){
			$('#userTypeDiv').hide();
		}
	}
	
	//初始化用户类型下拉框
	function initUserTypeSel(defaultVal){
		$.getApiClient('/user/userTypes').get().done(function(data){
			if(!data.payload){
				data.payload=[];
			}
		    multipleSelectData("user_type",[{"item_code": "", "item_name": "请选择"}].concat(data.payload), defaultVal, {valueAttr:'item_code', displayAttr:'item_name'},'请选择');
			$('#user_type').multipleSelect({width:'100%', single: true});
		});
	}
	
	//初始化所属医院级拉框
	function initHospitalSel(defaultHosVal,defaultDeptsVal){
		$.getApiClient('/baseInfo/hospitals').get().done(function(data){
			if(!data.payload){
				data.payload=[];
			}
		    multipleSelectData("hospital_id",[{"id": "", "hospital_name": "请选择"}].concat(data.payload), defaultHosVal, {valueAttr:'id', displayAttr:'hospital_name'},'请选择');
			$('#hospital_id').multipleSelect({width:'100%', single: true});
			
			//医院科室下拉框联动
			$('#hospital_id').change(function(){
				var hosid=$(this).children('option:selected').val();
				initDepartmentSel(hosid,defaultDeptsVal);
			}).change();
		});
	}
	
	//初始化所属科室下拉框
	function initDepartmentSel(hosId,defaultVal){
		if(hosId){
			$.getApiClient('/baseInfo/departments').setQuery({hospital_id:hosId}).get().done(function(data){
				if(!data.payload){
					data.payload=[];
				}
			    multipleSelectData("department_id",[{"id": "", "department_name": "请选择"}].concat(data.payload), defaultVal, {valueAttr:'id', displayAttr:'department_name'},"请选择");
				$('#department_id').multipleSelect({width:'100%', single: true});
			});
		}else{
			multipleSelectData("department_id",[{"id": "", "department_name": "请选择"}], defaultVal, {valueAttr:'id', displayAttr:'department_name'},"请选择");
			$('#department_id').multipleSelect({width:'100%', single: true});
		}
	}
	
	//初始化用户角色
	function initUserRoles(defaultVal){
		$.getApiClient('/role/roles').get().done(function(data){
			if(!data.payload){
				data.payload=[];
			}
			var rolesArray=[];
			$.each(data.payload,function(index,item){
				if(defaultVal){
					var defaultValArray=defaultVal.split(',')
					if($.inArray(item.id,defaultValArray) != -1){
						rolesArray.push('<label class="checkbox-inline"><input class="iradio_flat-red" type="checkbox" name="role_id" bindname="role_id" value="'+item.id+'" checked>'+item.role_name+'</label>');
					}else{
						rolesArray.push('<label class="checkbox-inline"><input class="iradio_flat-red" type="checkbox" name="role_id" bindname="role_id" value="'+item.id+'">'+item.role_name+'</label>');
					}
				}else{
					rolesArray.push('<label class="checkbox-inline"><input class="iradio_flat-red" type="checkbox" name="role_id" bindname="role_id" value="'+item.id+'">'+item.role_name+'</label>');
				}
			})
			$('#rolelist').html(rolesArray.join(''));
			initIcheck();
		});
	}
}

//事件绑定
function eventBind(type,userId){
	$('#cancel').click(function(){
		BootstrapDialog.closeAll();
	})
	
	if(type=='add'){
		$('#save').on('click',saveNewUser);
	}else{
		$('#save').on('click',function(){
			updateUser(userId);
		});
	}
}

//新增用户操作
function saveNewUser(){
	if(!$("#userForm").validationForm()){
		return;
	}
	
	if(!$('#user_type').multipleSelect('getSelects')[0]){
		customAlertDialog("用户类型需填写", '错误提示', null, null);
		return;
	}

	if(!$('#hospital_id').multipleSelect('getSelects')[0]){
		customAlertDialog("所属医院需填写", '错误提示', null, null);
		return;
	}
	
	if(!$('#department_id').multipleSelect('getSelects')[0]){
		customAlertDialog("所属科室需填写", '错误提示', null, null);
		return;
	}
	
	$.getApiClient('/user').post('#userForm', function(params){
		return $.extend(params, {
			hospital_name: $('#hospital_id').multipleSelect('getSelects','text')[0],
			department_name: $('#department_id').multipleSelect('getSelects','text')[0]
		});
	}).done(function(data){
		if(data.code == "0"){
			BootstrapDialog.closeAll();
			customTimeOutDialog('信息提示','保存成功',null,2000);
			pageQuery();
		}else{
			customAlertDialog(data.message, '错误提示', null, null);
		}
	});
}

//修改用户操作
function updateUser(userId){
	if(!$("#userForm").validationForm()){
		return;
	}
	
	if(userId!=loginUser.id){
		if(!$('#user_type').multipleSelect('getSelects')[0]){
			customAlertDialog("用户类型需填写", '错误提示', null, null);
			return;
		}
	}
	
	if(!$('#hospital_id').multipleSelect('getSelects')[0]){
		customAlertDialog("所属医院需填写", '错误提示', null, null);
		return;
	}
	
	if(!$('#department_id').multipleSelect('getSelects')[0]){
		customAlertDialog("所属科室需填写", '错误提示', null, null);
		return;
	}
	
	$.getApiClient('/user/{userid}').setQuery({
		userid:userId
	}).put('#userForm', function(params){
		if(userId==loginUser.id){
			return $.extend(params, {
				hospital_name: $('#hospital_id').multipleSelect('getSelects','text')[0],
				department_name: $('#department_id').multipleSelect('getSelects','text')[0],
				user_type: loginUser.user_type
			});
		}else{
			return $.extend(params, {
				hospital_name: $('#hospital_id').multipleSelect('getSelects','text')[0],
				department_name: $('#department_id').multipleSelect('getSelects','text')[0]
			});
		}

	}).done(function(data){
		if(data.code == "0"){
			BootstrapDialog.closeAll();
			customTimeOutDialog('信息提示','修改成功',null,2000);
			pageQuery();
		}else{
			customAlertDialog(data.message, '错误提示', null, null);
		}
	});
}